package cn.yunyichina.provider.base.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.yunyichina.provider.base.utils.CacheConstant;
import cn.yunyichina.provider.framework.data.SpringContextHandler;
import cn.yunyichina.provider.iface.entity.base.OrgSettingVo;
import cn.yunyichina.provider.iface.entity.base.OrgSettingVoResponse;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.yunyichina.provider.base.dao.OrgSettingDao;
import cn.yunyichina.provider.framework.dubbo.service.CacheService;
import cn.yunyichina.provider.iface.entity.base.OrgSetting;
import cn.yunyichina.provider.iface.entity.cache.SessionInfo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.utils.convert.JsonUtils;
import org.springframework.util.CollectionUtils;

/**
 * 
 * @projectName:yyt-provider-base
 * @author:yangfan
 * @description:医院配置信息
 * @date:2016年11月11日
 * @className:OrgsettingServiceImpl
 * @pakeage:cn.yunyichina.provider.base.service.impl
 */
@Service
public class OrgsettingServiceImpl {
	@Autowired
	private OrgSettingDao orgSettingDao;

	private static final Logger logger = LoggerFactory.getLogger(OrgsettingServiceImpl.class);

	/**
	 * 
	 * @methodName:updateOrgsetting
	 * @description:修改平台医院配置
	 * @author:yangfan
	 * @date:2016年11月14日
	 * @param data
	 * @param sessionId
	 * @return:Response
	 */
	public Response updateOrgsetting(String data, String sessionId) {
		Response response = new Response();
		Map<String, String> map = new HashMap<>();
		map = JsonUtils.parseObject(data, Map.class);
		SessionInfo session = CacheService.getSessionInfo(sessionId);
		if (null == session) {
			response.setResultCodeAndMessage("1101", "用户信息为空，请先登录");
			return response;
		}
		if (StringUtils.isBlank(map.get("id"))) {
			response.setResultCodeAndMessage("1101", "医院配置ID不能为空");
			return response;
		}
		if (StringUtils.isBlank(map.get("his_code"))) {
			response.setResultCodeAndMessage("1101", "医院代码不能为空");
			return response;
		}
		if (StringUtils.isBlank(map.get("medical_his_code"))) {
			response.setResultCodeAndMessage("1101", "医疗机构编码不能为空");
			return response;
		}
		if (StringUtils.isBlank(map.get("url"))) {
			response.setResultCodeAndMessage("1101", "接口ID不能为空");
			return response;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		OrgSetting orgSetting = new OrgSetting();
		orgSetting.setId(map.get("id"));
		orgSetting.setUpdateBy(session.getUserId());
		orgSetting.setUpdateTime(sdf.format(new Date()));
		this.orgSettingDao.update(orgSetting);
		return response;
	}

	/**
	 * 
	 * @methodName:selectOrgsetting
	 * @description:查询医院配置
	 * @author:yangfan
	 * @date:2016年11月15日
	 * @param data
	 * @return:Response
	 */
	public Response selectOrgsetting(String data) {
		Response response = new Response();
		OrgSetting org = JsonUtils.parseObject(data, OrgSetting.class);
		List<OrgSetting> orglist = this.orgSettingDao.select(org);
		response.setResult(JsonUtils.toJsonString(orglist));
		response.setResultCodeAndMessage("0", "查询成功");
		return response;
	}

	/**
	 * 
	 * @methodName:insertOrgsetting
	 * @description:新增配置
	 * @author:yangfan
	 * @date:2016年11月16日
	 * @param data
	 * @param sessionId
	 * @return
	 * @return:Response
	 */
	public Response insertOrgsetting(String data, String sessionId) {
		Response response = new Response();
		Map<String, String> map = JsonUtils.parseObject(data, Map.class);
		if (StringUtils.isBlank(map.get(""))) {
			
		} else {

		}
		if (StringUtils.isBlank(map.get(""))) {

		} else {

		}
		if (StringUtils.isBlank(map.get(""))) {

		} else {

		}
		if (StringUtils.isBlank(map.get(""))) {

		} else {

		}
		if (StringUtils.isBlank(map.get(""))) {

		} else {

		}
		if (StringUtils.isBlank(map.get(""))) {

		} else {

		}
		OrgSetting org = new OrgSetting();
		this.orgSettingDao.insert(org);
		updateOrgsettingCache(org);
		return response;
	}

	/**
	 * 刷新医院配置缓存
	 * yyt.base.orgsetting.cache.reload
	 * @param data
	 * @return
	 */
	public Response reloadOrgsettingCache(String data, String sessionId) {
		Response response = new Response();
		OrgSettingVo vo = JsonUtils.parseObject(data, OrgSettingVo.class);

		OrgServiceImpl orgServiceImpl = (OrgServiceImpl) SpringContextHandler.getBean("orgServiceImpl");
		ResCommon<List<OrgSettingVoResponse>> resCommon = orgServiceImpl.getOrgSettingList(vo);
		if(!"0".equals(resCommon.getResultCode())){
			response.setResultCodeAndMessage(resCommon.getResultCode(),resCommon.getResultMessage());
			return response;
		}

		List<OrgSettingVoResponse> orgSettingList = resCommon.getResult();

		if(!CollectionUtils.isEmpty(orgSettingList)){
			for(OrgSettingVoResponse orgSetting:orgSettingList) {
				String field = StringUtils.isNotBlank(orgSetting.getBranchCode()) ? (orgSetting.getOrgCode() + ":" + orgSetting.getBranchCode()) : orgSetting.getOrgCode();
				//删除掉methodCode的缓存
				CacheService.delGlobalKeyHash(CacheConstant.CACHE_BASE_MODULE, CacheConstant.CACHE_ORG_SETTING_REGION,
						CacheConstant.CACHE_HASH_KEY, field+ ":" + vo.getMethodCode());
				if(StringUtils.isNotBlank(orgSetting.getMethodCode())){
					field += ":" + orgSetting.getMethodCode();
				}
				CacheService.setGlobalKeyHash(CacheConstant.CACHE_BASE_MODULE, CacheConstant.CACHE_ORG_SETTING_REGION,
						CacheConstant.CACHE_HASH_KEY, field, JsonUtils.toJsonString(orgSetting));
			}
		}

		response.setResult(JsonUtils.toJsonString(orgSettingList));
		response.setResultCodeAndMessage("0", "更新缓存成功");
		return response;
	}

	/**
	 * 更新医院配置缓存，内部调用
	 * @param orgSetting
     */
	private void updateOrgsettingCache(OrgSetting orgSetting) {
		String field = StringUtils.isNotBlank(orgSetting.getBranchCode()) ? (orgSetting.getOrgCode() + ":" + orgSetting.getBranchCode()) : orgSetting.getOrgCode();
		CacheService.setGlobalKeyHash(CacheConstant.CACHE_BASE_MODULE, CacheConstant.CACHE_ORG_SETTING_REGION,
		CacheConstant.CACHE_HASH_KEY, field, JsonUtils.toJsonString(orgSetting));

	}
}
